package com.ayoka.parenting.ui.live;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.ayoka.parenting.R;
import com.ayoka.parenting.adapter.MessageAdapter;
import com.ayoka.parenting.bean.ChatMessageBean;
import com.ayoka.parenting.bean.BasicUserInfoBean;
import com.ayoka.parenting.interf.EndlessRecyclerOnScrollListener;
import com.ayoka.parenting.interf.SimpleTextWatchListener;
import com.ayoka.parenting.widget.MessageEditText;
import com.jincp.common.brvah.layoutmanager.MyLinearLayoutManager;
import com.jincp.common.dialog.BaseDialogBuilder;
import com.jincp.common.dialog.BaseDialogFragment;
import com.jincp.common.utils.LiveDataBus;
import com.jincp.common.utils.MyLogger;
import com.jincp.common.utils.TDevice;
import com.tencent.imsdk.TIMMessage;

import java.util.List;

/**
 * =========================================================
 *
 * @ProjectName:
 * @ClassName: ChatDialog
 * @Description:
 * @Author: jincp
 * @CreateDate: 2019/9/19 16:12
 * =========================================================
 */
public class ChatDialog extends BaseDialogFragment {

    private final static String MASK_STR = "@";

    private MessageProvider messageProvider;

    private MessageAdapter messageAdapter;
    private RecyclerView recyclerView;

    private MessageEditText etMessageInput;

    private boolean isGettingMessage = false;

    private ChatMessageBean topChatMessageBean;

    public static ChatDialog newInstance(Builder builder) {
        ChatDialog dialog = new ChatDialog();
        Bundle bundle = getArgumentBundle(builder);
        dialog.setArguments(bundle);
        return dialog;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LiveDataBus.getInstance().with("ChatMessage", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String operation) {
                if (messageAdapter == null) return;
                isGettingMessage = false;
                if (TextUtils.equals(operation, "Receive")) {
                    int index = messageAdapter.getItemCount() - 1;
                    try {
                        messageAdapter.notifyItemInserted(index);
                    } catch (Exception e) {
                        messageAdapter.notifyDataSetChanged();
                    }
                    recyclerView.scrollToPosition(index);
                } else if (TextUtils.equals(operation, "Load")) {
                    try {
                        int indexOf = messageAdapter.getData().indexOf(topChatMessageBean);
                        messageAdapter.notifyItemRangeInserted(0, indexOf);
                    } catch (Exception e) {
                    }
                } else if (TextUtils.equals(operation, "Send")) {
                    int index = messageAdapter.getItemCount() - 1;
                    try {
                        messageAdapter.notifyItemInserted(index);
                    } catch (Exception e) {
                        messageAdapter.notifyDataSetChanged();
                    }
                    recyclerView.scrollToPosition(index);
                    etMessageInput.setText("");
                }
            }
        });
    }

    @Override
    protected void convertView(@Nullable View container, final BaseDialogFragment dialogFragment) {
        if (container == null) return;
        container.findViewById(R.id.iv_close).setOnClickListener(new CloseClickListener());

        recyclerView = container.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new MyLinearLayoutManager(getActivity()));
        messageAdapter = new MessageAdapter();
        messageAdapter.bindToRecyclerView(recyclerView);
        if (messageProvider != null) {
            messageAdapter.setNewData(messageProvider.getChatMessageList());
        }
        recyclerView.scrollToPosition(messageAdapter.getItemCount() - 1);
        recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener() {

            @Override
            public void onTopLoadMore(int lastItemPosition) {
                if (!isGettingMessage) {
                    isGettingMessage = true;
                    //如果拉到顶端读取更多消息
                    topChatMessageBean = messageAdapter.getItem(0);
                    if (topChatMessageBean != null) {
                        MyLogger.d(TAG, "ChatMessageBean = " + topChatMessageBean.message);
                        messageProvider.loadMoreMessage(topChatMessageBean.data);
                    }
                }
            }
        });

        etMessageInput = container.findViewById(R.id.et_message_input);
        final Button btnSend = container.findViewById(R.id.btn_send);
        etMessageInput.addTextChangedListener(new SimpleTextWatchListener() {

            @Override
            public void afterTextChanged(Editable s) {
                btnSend.setEnabled(s.length() != 0);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count == 1 && s.charAt(start) == MASK_STR.charAt(0)) { //添加一个字
                    //跳转到@界面
                    if (mDialogResultListener != null) {
//                        CourseClassroomMemberActivity.setUserBeanData(messageProvider.getUserBeanList());
//                        CourseClassroomMemberActivity.start(ChatDialog.this, true);
                    }
                }
            }
        });

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userId = etMessageInput.getUserIdString();
                String message = etMessageInput.getMessageString();
                if (TextUtils.isEmpty(userId)) {
                    if (!TextUtils.isEmpty(message) && mDialogResultListener != null) {
                        mDialogResultListener.result(ChatDialog.this, new String[]{"sendGroupTextMessage", message});
                        btnSend.setEnabled(false);
                    }
                } else {
                    if (!TextUtils.isEmpty(message) && mDialogResultListener != null) {
                        mDialogResultListener.result(ChatDialog.this, new String[]{"sendTextMessage", userId, message});
                        btnSend.setEnabled(false);
                    }
                }
                TDevice.hideSoftKeyboard(etMessageInput);
            }
        });
    }

    public void setMessageProvider(MessageProvider messageProvider) {
        this.messageProvider = messageProvider;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_chat;
    }

    public static class Builder extends BaseDialogBuilder<Builder, ChatDialog> {

        @Override
        public ChatDialog build() {
            return ChatDialog.newInstance(this);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && data != null) {
            BasicUserInfoBean userBean = (BasicUserInfoBean) data.getSerializableExtra("UserBean");
            if (userBean != null) {
                etMessageInput.addAtSpan(null, userBean.WeixinNickName, String.valueOf(userBean.ID));
            }
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        TDevice.hideSoftKeyboard(etMessageInput);
    }

    public interface MessageProvider {
        List<BasicUserInfoBean> getUserBeanList();

        List<ChatMessageBean> getChatMessageList();

        void loadMoreMessage(TIMMessage message);
    }
}